package com.budwk.app.sqfwV2.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.exception.ServiceException;
import com.budwk.app.oss.services.SysOssService;
import com.budwk.app.sqfw.component.CommonComponent;
import com.budwk.app.sqfw.constants.DictConstants;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_completeflow;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.models.Sqfw_form_summary_pdf;
import com.budwk.app.sqfw.services.SqfwCompleteflowService;
import com.budwk.app.sqfw.services.SqfwFormSummaryPdfService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.dto.TemplateCodeUpdateDTO;
import com.budwk.app.sqfwV2.component.BinyangStreetComponent;
import com.budwk.app.sqfwV2.component.SummarySafetyCommponent;
import com.budwk.app.sqfwV2.component.centuryCity.CenturyCitySecurityExcelService;
import com.budwk.app.sqfwV2.component.centuryCity.CenturyCitySecurityPdfService;
import com.budwk.app.sqfwV2.dto.dto.centuryCity.SafeCheckGasDTO;
import com.budwk.app.sqfwV2.dto.dto.centuryCity.SafeCheckTaskParamDataDTO;
import com.budwk.app.sqfwV2.dto.dto.centuryCity.SafeCheckTaskPdfDTO;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownExcelLedgerReqVo;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownFileTypesResVo;
import com.budwk.app.sqfwV2.dto.entity.SqfwShopsBaseInfo;
import com.budwk.app.sqfwV2.enums.*;
import com.budwk.app.sqfwV2.enums.jinYang.JinYangExcelEnum;
import com.budwk.app.sqfwV2.generator.binyangStreet.excel.CampusTrainingOffExcel;
import com.budwk.app.sqfwV2.generator.binyangStreet.excel.EnterpriseSafetyInvestigationExcel;
import com.budwk.app.sqfwV2.generator.binyangStreet.excel.LargeCompanySafeGenerator;
import com.budwk.app.sqfwV2.generator.binyangStreet.excel.logisticsWarehouseExcelGenerator;
import com.budwk.app.sqfwV2.service.CenturyCitySecurityService;
import com.budwk.app.sqfwV2.service.ShopsBaseInfoService;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysDictService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.sys.vo.SysDictVO;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.security.utils.SecurityUtil;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.util.cri.SimpleCriteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Slf4j
@IocBean(name = "centuryCitySecurityService")
public class CenturyCitySecurityServiceImpl implements CenturyCitySecurityService {

    @Inject
    private CenturyCitySecurityPdfService centuryCitySecurityPdfService;
    @Inject
    private CenturyCitySecurityExcelService centuryCitySecurityExcelService;
    @Inject
    private SysDictService sysDictService;
    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;
    @Inject("taskQueryExecutor")
    private ThreadPoolExecutor taskQueryExecutor;
    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;

    @Inject
    private ShopsBaseInfoService shopsBaseInfoService;

    @Inject
    private SqfwFormSummaryPdfService formSummaryPdfService;
    @Inject
    private SysOssService sysOssService;

    @Inject
    private SysUserService userService;

    @Inject
    private SummarySafetyCommponent summarySafetyCommponent;

    ExecutorService executorService = Executors.newFixedThreadPool(50);

    @Override
    public Result<?> downExcelLedger(DownExcelLedgerReqVo reqVo) {
        List<ExcelCreateConfig> excelConfigList = CommonComponent.getExcelConfigList(reqVo);
        List<GenerateExcelUrlVO> generateExcelUrlVOS = centuryCitySecurityExcelService.generateExcel(excelConfigList, SecurityUtil.getUserId(), reqVo.getSqfwIds());
        return Result.data(generateExcelUrlVOS);
    }

    private BinYangFileServiceEnum isBinYangPdf(DownExcelLedgerReqVo reqVo) {
        BinYangFileServiceEnum serviceEnum = BinYangFileServiceEnum.getByCode(reqVo.getExcelCodes().get(0));
        if (serviceEnum != null) {
            return serviceEnum;
        }
        return serviceEnum;
    }

    @Override
    public Result<?> downPdfLedger(DownExcelLedgerReqVo reqVo) {
        List<GenerateExcelUrlVO> generateExcelUrlVOS = new ArrayList<>();
        GenerateExcelUrlVO generateExcelUrlVO = new GenerateExcelUrlVO();
        generateExcelUrlVOS.add(generateExcelUrlVO);
        if (reqVo.isDownTemplate()) {
            String filePath = null;
            String fileName = null;
            BinYangFileServiceEnum pdf = isBinYangPdf(reqVo);
            if (pdf != null) {
                filePath = pdf.getTemplatePath();
                fileName = pdf.getFileName();
                int lastSymbolIndex = fileName.lastIndexOf(".");
                if (lastSymbolIndex == -1) {
                    fileName = fileName + ".docx";
                }
            } else {
                if ("V2".equals(reqVo.getSource())) {
                    filePath = SafetyCheckV2NewEnums.getUrl(Integer.valueOf(reqVo.getExcelCodes().get(0)));
                } else {
                    filePath = SafetyCheckV2Enums.getUrl(Integer.valueOf(reqVo.getExcelCodes().get(0)));
                }
                fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
            }
            generateExcelUrlVO.setExcelUrl(sysOssService.upload(CommonFormOfficeUtils.getTempPdfFile(filePath), fileName).getUrl());
        } else {
            boolean isMultiple = false;
            Cnd cnd = Cnd.NEW();
            BinYangFileServiceEnum pdf = isBinYangPdf(reqVo);
            if (pdf != null) {
                cnd.and(" param_data->>'type'", "=", pdf.getLabel());
            } else {
                cnd.and(" param_data->>'type'", "=", SafetyCheckV2Enums.getName(Integer.valueOf(reqVo.getExcelCodes().get(0))));
            }
            Set<String> isMultipleSet = Sets.newHashSet(String.valueOf(SafetyCheckV2Enums.A.getCode()), String.valueOf(SafetyCheckV2Enums.C.getCode())
                    , String.valueOf(SafetyCheckV2Enums.G.getCode()), String.valueOf(SafetyCheckV2Enums.K.getCode()), String.valueOf(SafetyCheckV2Enums.L.getCode()));
            /*
            if (reqVo.getExcelCodes().get(0).equals(String.valueOf(SafetyCheckV2Enums.G.getCode()))
                    || reqVo.getExcelCodes().get(0).equals(String.valueOf(SafetyCheckV2Enums.K.getCode()))) {
                //cnd.and(" param_data->>'placeType'", "in", Arrays.asList(CenturyCitySafePlaceTypeEnum.RESTAURANT.getName(), CenturyCitySafePlaceTypeEnum.SHOP.getName()));
                isMultiple = true;
            }
            */
            //修改，只要包含一个就是多文件
            if (isMultipleSet.contains(reqVo.getExcelCodes().get(0))) {
                isMultiple = true;
            }

            if (StringUtils.isNotBlank(reqVo.getFillStartDate())) {
                cnd.and(Sqfw_formSummary_new::getFillDate, ">=", String.format("%s 00:00:00", reqVo.getFillStartDate()));
                Sys_user user = userService.getUserById(SecurityUtil.getUserId());
                cnd.and(Sqfw_formSummary_new::getProvince, "=", user.getProvince());
                cnd.and(Sqfw_formSummary_new::getCity, "=", user.getCity());
                cnd.and(Sqfw_formSummary_new::getDistrict, "=", user.getDistrict());
                cnd.and(Sqfw_formSummary_new::getCounty, "=", user.getCounty());
                cnd.and(Sqfw_formSummary_new::getCommunity, "=", user.getCommunity());
            } else {
                cnd.and(Sqfw_formSummary_new::getSqfwId, "in", reqVo.getSqfwIds());
            }
            if (StringUtils.isNotBlank(reqVo.getFillEndDate())) {
                cnd.and(Sqfw_formSummary_new::getFillDate, "<=", String.format("%s 23:59:59", reqVo.getFillEndDate()));
            }
            if (StringUtils.isNotBlank(reqVo.getShopInfoId())) {
                cnd.and(Sqfw_formSummary_new::getShopsBaseInfoId, "=", reqVo.getShopInfoId());
            }
            cnd.and(Sqfw_formSummary_new::getType, "=", SupportBusinessTypeEnum.SAFE_CHECK.getName());
            //cnd.and(Sqfw_formSummary_new::getSqfwId, "in", reqVo.getSqfwIds());
            cnd.desc(Sqfw_formSummary_new::getFillDate);
            List<Sqfw_formSummary_new> sqfwFormSummaryNews = sqfwFormsummaryNewService.query(cnd);
            if (CollectionUtil.isNotEmpty(sqfwFormSummaryNews)) {
                if (isMultiple) {
                    //zhangp 2024-03-06 九小场所-餐饮走这个
                    List<String> SummaryIdS = sqfwFormSummaryNews.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList());
                    List<Sqfw_form_summary_pdf> sqfwFormSummaryPdfs = formSummaryPdfService.query(Cnd.where(Sqfw_form_summary_pdf::getSummaryId, "in", SummaryIdS)
                            .and(Sqfw_form_summary_pdf::getIndex, "=", reqVo.getExcelCodes().get(0))
                            .and(Sqfw_form_summary_pdf::getStatus, "=", "2")
                            .asc(Sqfw_form_summary_pdf::getCreateDate));
                    if (!sqfwFormSummaryPdfs.isEmpty()) {
                        List<String> pdfPathList = sqfwFormSummaryPdfs.stream().map(Sqfw_form_summary_pdf::getUrl).collect(Collectors.toList());
                        if (pdf != null) {
                            String url = CommonFormOfficeUtils.createConvergePdfAndUpload(pdfPathList, pdf.getName());
                            generateExcelUrlVO.setExcelUrl(url);
                        } else {
                            String url = CommonFormOfficeUtils.createConvergePdfAndUpload(pdfPathList, SafetyCheckV2Enums.getmergePdf(Integer.valueOf(reqVo.getExcelCodes().get(0))));
                            generateExcelUrlVO.setExcelUrl(url);
                        }
                    }
                } else {
                    List<String> sqfwFlowIdList = sqfwFormSummaryNews.stream().map(Sqfw_formSummary_new::getSqfwFlowId).collect(Collectors.toList());
                    List<Sqfw_completeflow> flwoList = sqfwCompleteflowService.query(Cnd.where(Sqfw_completeflow::getId, "in", sqfwFlowIdList)
                            .and(Sqfw_completeflow::getFileType, "like", SqfwFormSummaryConstants.safety_check + "%")//老版本是前端传上来的，2.0是后端生成的结果只不一样，多了两个字“整治”
                            .and(Sqfw_completeflow::getResourcePath, "!=", "creating")
                            .and(Sqfw_completeflow::getResourcePath, "!=", "error"));
                    if (!flwoList.isEmpty()) {
                        List<String> pdfPathList = flwoList.stream().map(Sqfw_completeflow::getResourcePath).collect(Collectors.toList());
                        if (pdf != null) {
                            String url = CommonFormOfficeUtils.createConvergePdfAndUpload(pdfPathList, pdf.getName());
                            generateExcelUrlVO.setExcelUrl(url);
                        } else {
                            String url = CommonFormOfficeUtils.createConvergePdfAndUpload(pdfPathList, SafetyCheckV2Enums.getmergePdf(Integer.valueOf(reqVo.getExcelCodes().get(0))));
                            generateExcelUrlVO.setExcelUrl(url);
                        }
                    }
                }
            }
        }
        return Result.data(generateExcelUrlVOS);
    }

    @Override
    public Sqfw_formSummary_new submitData(TemplateCodeUpdateDTO dto) {
        Sqfw_formSummary_new sqfwFormSummaryNew = dto.getFormSummary();
        SafeCheckTaskPdfDTO safeCheckTaskPdfDTO = JSONObject.parseObject(sqfwFormSummaryNew.getParamData(), SafeCheckTaskPdfDTO.class);
        List<SafeCheckTaskParamDataDTO> safeCheckTaskParamDataDTOList = safeCheckTaskPdfDTO.getHiddenDanger();
        List<SafeCheckTaskParamDataDTO> otherHiddenDangers = safeCheckTaskPdfDTO.getOtherHiddenDangers();
        sqfwFormSummaryNew.setIssueStatus("0");
        summarySafetyCommponent.createOneTask(dto, null, SupportBusinessTypeEnum.SAFE_CHECK.getName());
        // 如果是宾阳街道数据 不走以下代码检查
        BinYangFileServiceEnum serviceEnum = BinYangFileServiceEnum.getByLabel(safeCheckTaskPdfDTO.getType(), sqfwFormSummaryNew.getDistrict(), sqfwFormSummaryNew.getCounty());
        if (serviceEnum != null) {
            centuryCitySecurityPdfService.generatePdfAndMessage(SecurityUtil.getUserId(), dto);
            return dto.getFormSummary();
        }
        // 重点场所和楼宇单独判断灭火器数量来检查是否有隐患
        if (CenturyCitySafeServiceEnum.CENTER_CITY_BUILDING_HAZARDS.getType().equals(safeCheckTaskPdfDTO.getType())
                || CenturyCitySafeServiceEnum.CENTER_CITY_KEY_LOCATION.getType().equals(safeCheckTaskPdfDTO.getType())) {
            if (HiddenDangerEnum.fireNum.getFlag().equals(safeCheckTaskPdfDTO.getPlaceFireExtinguishersNumber())) {
                sqfwFormSummaryNew.setIssueStatus("1");
            }
        }
        if ("0".equals(sqfwFormSummaryNew.getIssueStatus())) {
            for (SafeCheckTaskParamDataDTO item : safeCheckTaskParamDataDTOList) {
                if (CenturyCitySafeServiceEnum.CENTER_CITY_NINE_SMALL_PLACE.getType().equals(safeCheckTaskPdfDTO.getType())
                        && HiddenDangerEnum.isHydrantOperational.getCode().equals(item.getRiskCode())) {
                    //九小场所-消防栓是否配备水枪，水带 只做记录不计入问题
                    continue;
                }
                HiddenDangerEnum hiddenDangerEnum = HiddenDangerEnum.getHiddenDangerEnumByCode(item.getRiskCode());
                if (null == hiddenDangerEnum) continue;
                if (hiddenDangerEnum.getFlag().equals(item.getKey())) {
                    sqfwFormSummaryNew.setIssueStatus("1");
                    break;
                }
            }
        }
        if ("0".equals(sqfwFormSummaryNew.getIssueStatus())) {
            if (CollectionUtil.isNotEmpty(otherHiddenDangers)) {
                for (SafeCheckTaskParamDataDTO otherHiddenDanger : otherHiddenDangers) {
                    if (StrUtil.isNotBlank(otherHiddenDanger.getRectificationType())) {
                        sqfwFormSummaryNew.setIssueStatus("1");
                    }

                }

            }
        }
        dto.setFormSummary(sqfwFormSummaryNew);
        centuryCitySecurityPdfService.generatePdfAndMessage(SecurityUtil.getUserId(), dto);
        return dto.getFormSummary();
    }

    @Override
    public Result<List<DownFileTypesResVo>> listDownFileTypes(String sqfwId) {
        // 1 获取所有字典数据
        List<SysDictVO> vos = sysDictService.listDictByCode(DictConstants.CENTER_CITY_EXCEL_TYPES);
        // 2 按照社区服务id查询数据
        String sqfwFormSummaryType = SupportBusinessTypeEnum.SAFE_CHECK.getName();
        Cnd cnd = Cnd.NEW();
        cnd.where().andEquals(Sqfw_formSummary_new::getSqfwId, sqfwId).andEquals(Sqfw_formSummary_new::getType, sqfwFormSummaryType);
        List<Sqfw_formSummary_new> list = sqfwFormsummaryNewService.query(cnd);
        // 检查数据是否可生成
        List<DownFileTypesResVo> results = new ArrayList<>();
        for (SysDictVO vo : vos) {
            DownFileTypesResVo resVo = new DownFileTypesResVo();
            resVo.setFileCode(vo.getCode()).setFileName(vo.getName()).setHiveData(list.size() > 0).setCreatedAt(vo.getCreatedAt()).setFileType("excel");
            results.add(resVo);
        }
        // 排序
        List<DownFileTypesResVo> resVos = results.stream().sorted(Comparator.comparing(DownFileTypesResVo::getCreatedAt).reversed()).collect(Collectors.toList());
        // 安全排查表pdf
      /*  DownFileTypesResVo resVo = new DownFileTypesResVo();
        resVo.setFileName(CenturyCitySafeServiceEnum.NINE_SMALL_PLACES_SAFETY.getName() + ".pdf")
                .setFileCode(CenturyCitySafeServiceEnum.NINE_SMALL_PLACES_SAFETY.getCode())
                .setHiveData(list.size() > 0)
                .setCreatedAt(System.currentTimeMillis())
                .setFileType("pdf");
        resVos.add(resVo);*/
        return Result.data(resVos);
    }

    @Override
    public Result<?> reGeneratePDF(String sqfwFlowId) {
        centuryCitySecurityPdfService.reGeneratePDF(sqfwFlowId);
        return Result.success();
    }

    @Override
    public List<String> getCheckDataIndexList(List<String> sqfwIdList) {
        log.info("centuryCity CheckDataIndexList111 param: {}", JSONObject.toJSONString(sqfwIdList));
        Cnd cnd = Cnd.NEW();
        cnd.and("sqfw_id", "in", sqfwIdList).and("type", "=", SupportBusinessTypeEnum.SAFE_CHECK.getName());
        List<Sqfw_formSummary_new> sqfwFormSummaryNewList = sqfwFormsummaryNewService.query(cnd);
        List<String> indexList = Lists.newArrayList();
        if (sqfwFormSummaryNewList.isEmpty()) {
            return Lists.newArrayList();
        }
        List<String> typeList = sqfwFormSummaryNewList.stream().map(m -> JSONObject.parseObject(m.getParamData(), SafeCheckTaskPdfDTO.class).getType()).distinct().collect(Collectors.toList());

        for (CenturyCitySafeServiceEnum item : CenturyCitySafeServiceEnum.values()) {
            if (typeList.contains(item.getType())) {
                if (item.getCode().equals(CenturyCitySafeServiceEnum.CENTER_CITY_FOOD_SAFE.getCode())) {
                    List<String> arrayList = new ArrayList<>();
                    arrayList.add(CenturyCitySafePlaceTypeEnum.RESTAURANT.getName());
                    arrayList.add(CenturyCitySafePlaceTypeEnum.SHOP.getName());
                    Cnd c = Cnd.NEW();
                    c.and("sqfw_id", "in", sqfwIdList).and("type", "=", SupportBusinessTypeEnum.SAFE_CHECK.getName());
                    c.and("param_data ->>'type'", "=", CenturyCitySafeServiceEnum.CENTER_CITY_FOOD_SAFE.getType())
//                            .and("param_data ->>'placeType'", "in", arrayList)
                            .and("param_data->>'fileOutputType'", "<>", "[\"-1\"]");
                    c.and(Cnd.exps("param_data ->>'transferToMarketSupervisionAndManagement'", "=", "是").or("param_data ->>'transferToMarketSupervisionAndManagement'", "=", "否"));
                    //zhangp 2024-03-26 根据选择餐饮店面销售检测文档 开始
                    c.orderBy("create_date", "asc");
                    checkFoodData(c, indexList, item);
                    //zhangp 2024-03-26 根据选择餐饮店面销售检测文档 结束
                } else if (item.getCode().equals(CenturyCitySafeServiceEnum.CENTER_CITY_GAS_SAFE.getCode())) {
                    //燃气检测
                    Cnd c = Cnd.NEW();
                    c.and("sqfw_id", "in", sqfwIdList).and("type", "=", SupportBusinessTypeEnum.SAFE_CHECK.getName());
                    c.and("param_data ->>'type'", "=", CenturyCitySafeServiceEnum.CENTER_CITY_GAS_SAFE.getType());
                    c.orderBy("create_date", "asc");
                    List<Sqfw_formSummary_new> sqfwFormSummaryNews = this.sqfwFormsummaryNewService.query(c);
                    for (Sqfw_formSummary_new sqfwItem : sqfwFormSummaryNews) {
                        SafeCheckTaskPdfDTO safeCheckTaskPdfDTO = JSONObject.parseObject(sqfwItem.getParamData(), SafeCheckTaskPdfDTO.class);
                        SafeCheckGasDTO safeCheckGasDTO = safeCheckTaskPdfDTO.getSafeCheckGasDTO();
                        if (ObjectUtils.isEmpty(safeCheckGasDTO)) continue;
                        CenturyCitySafeCheckGasUseEnum centuryCitySafeCheckGasUseEnum = CenturyCitySafeCheckGasUseEnum.getEnum(safeCheckGasDTO.getFireAndElectricityUsage());
                        if (ObjectUtils.isNotEmpty(centuryCitySafeCheckGasUseEnum)) {
                            indexList.add(item.getCode());
                            break;
                        }
                    }
                } else if (item.getCode().equals(CenturyCitySafeServiceEnum.CENTER_CITY_PERSONNEL_DENSITY.getCode())) {
                    //人员密集
                    //excel
                    indexList.add(item.getCode());
                    //pdf
                    indexList.add(String.valueOf(SafetyCheckV2Enums.C.getCode()));
                    Cnd c = Cnd.NEW();
                    c.and("sqfw_id", "in", sqfwIdList).and("type", "=", SupportBusinessTypeEnum.SAFE_CHECK.getName());
                    c.and("param_data ->>'type'", "=", CenturyCitySafeServiceEnum.CENTER_CITY_PERSONNEL_DENSITY.getType())
                            .and("param_data->>'whetherItIsASchool'", "=", "true");
                    //zhangp 2024-05-15 人员密集食堂
                    c.orderBy("create_date", "asc");
                    List<Sqfw_formSummary_new> sqfwFormSummaryNews = this.sqfwFormsummaryNewService.query(c);
                    if (!sqfwFormSummaryNews.isEmpty()) {
                        //食堂
                        indexList.add(String.valueOf(SafetyCheckV2Enums.L.getCode()));
                    }
                } else {
                    //excel
                    indexList.add(item.getCode());
                    //pdf
                    indexList.add(String.valueOf(SafetyCheckV2Enums.getCodeByName(item.getType())));
                }
            }
        }
        // 宾阳街道数据检查
        log.info("centuryCity CheckDataIndexList111 param: {}, indexList: {}", JSONObject.toJSONString(typeList), indexList);
        BinyangStreetComponent.getCheckDataIndexList(typeList, sqfwFormSummaryNewList, indexList);

        // 宇虹
        if (typeList.contains(YuHongEnum.BACK_PAY.getType())) {
            // 欠薪风险
            indexList.add(YuHongEnum.BACK_PAY.getCode());
        }

        return indexList;
    }

    private void checkFoodData(Cnd c, List<String> indexList, CenturyCitySafeServiceEnum item) {
        List<Sqfw_formSummary_new> sqfwFormSummaryNews = sqfwFormsummaryNewService.query(c);
        if (!indexList.contains(CenturyCitySafeServiceEnum.CENTER_CITY_NINE_SMALL_PLACE.getCode())) {
            //excel
            indexList.add(item.getCode());
            //pdf
            indexList.add(String.valueOf(SafetyCheckV2Enums.getCodeByName(item.getType())));
        }
        if (!sqfwFormSummaryNews.isEmpty()) {
            //excel
            indexList.add(CenturyCitySafeServiceEnum.CENTER_CITY_FOOD_SAFE.getCode());
            int count = 0;
            for (Sqfw_formSummary_new sfn : sqfwFormSummaryNews) {
                SafeCheckTaskPdfDTO safeCheckTaskPdfDTO = JSONObject.parseObject(sfn.getParamData(), SafeCheckTaskPdfDTO.class);
                //这里为了兼容老数据因此是空的情况下之前的都会生成
                if (ObjectUtil.isEmpty(safeCheckTaskPdfDTO.getFileOutputType()) || safeCheckTaskPdfDTO.getFileOutputType().isEmpty()) {
                    //pdf
                    indexList.add(String.valueOf(SafetyCheckV2Enums.G.getCode()));
                    indexList.add(String.valueOf(SafetyCheckV2Enums.K.getCode()));
                    break;
                } else {
                    //餐饮服务日常巡查表合集
                    String G = String.valueOf(SafetyCheckV2Enums.G.getCode());
                    //食品销售日常巡查表合集
                    String K = String.valueOf(SafetyCheckV2Enums.K.getCode());

                    if (!indexList.contains(G) && safeCheckTaskPdfDTO.getFileOutputType().contains(G)) {
                        count++;
                        indexList.add(G);
                    }
                    if (!indexList.contains(K) && safeCheckTaskPdfDTO.getFileOutputType().contains(K)) {
                        count++;
                        indexList.add(K);
                    }
                }
                if (count == 2) {
                    break;
                }
            }
        }
    }

    @Override
    public Result<?> listByConditionKey(String conditionKey, String content, String type) {

        List<SqfwShopsBaseInfo> sqfwShopsBaseInfos = shopsBaseInfoService.getShopInfoByPlaceName(content, null, null, null);
        if (sqfwShopsBaseInfos.isEmpty()) {
            return Result.success();
        }
        List<Sqfw_formSummary_new> result = new ArrayList<>();
        // 取出所有的id
        List<String> shopsIds = sqfwShopsBaseInfos.stream().map(SqfwShopsBaseInfo::getId).collect(Collectors.toList());
        SimpleCriteria cri = Cnd.cri();
        SqlExpressionGroup criSql = cri.where();
        //criSql.andEquals(Sqfw_formSummary_new::getUnitId, SecurityUtil.getUnitId())
        criSql.andIn(Sqfw_formSummary_new::getShopsBaseInfoId, shopsIds.toArray(new String[0]))
                .andEquals(Sqfw_formSummary_new::getType, type);
        cri.getOrderBy().desc(Sqfw_formSummary_new::getFillDate);
        List<Sqfw_formSummary_new> list = sqfwFormsummaryNewService.query(cri);
        if (list.isEmpty()) {
            //return Result.success();
            //当无记录时构建商铺数据
            return Result.data(buildParamData(sqfwShopsBaseInfos));
        } else {
            // 按照最新的时间和场所名称去重
            Set<String> ps = new HashSet<>();
            // 按照时间排序
            List<Sqfw_formSummary_new> queryList = list.stream().sorted(Comparator.comparing(Sqfw_formSummary_new::getFillDate).reversed())
                    .collect(Collectors.toList());
            for (Sqfw_formSummary_new summaryNew : queryList) {
                Optional<String> optional = ps.stream().filter(e -> e.equals(summaryNew.getShopsBaseInfoId())).findAny();
                if (optional.isEmpty()) {
                    ps.add(summaryNew.getShopsBaseInfoId());
                    summaryNew.setShopsBaseInfo(sqfwShopsBaseInfos.stream().filter(e -> e.getId().equals(summaryNew.getShopsBaseInfoId())).findFirst().get());
                    result.add(summaryNew);
                }
            }
            buildAndAddParamData(result, ps, sqfwShopsBaseInfos);
        }

        return Result.data(result);
    }

    @Override
    public Result<?> getShopInfoListByContent(String content, Integer pageSize, Integer pageNo) {

        return Result.data(shopsBaseInfoService.getShopInfoByPlaceName(content, pageSize, pageNo, SupportBusinessTypeEnum.SAFETY_CHECK.getCode()));
    }

    @Override
    public Result<?> getFormSummaryInfoListByShopId(String shopBaseInfoId) {
        SimpleCriteria cri = Cnd.cri();
        SqlExpressionGroup criSql = cri.where();
        criSql.andEquals(Sqfw_formSummary_new::getShopsBaseInfoId, shopBaseInfoId)
                .andEquals(Sqfw_formSummary_new::getType, SupportBusinessTypeEnum.SAFE_CHECK.getName());
        cri.getOrderBy().desc(Sqfw_formSummary_new::getFillDate);
        Sqfw_formSummary_new formSummaryNew = sqfwFormsummaryNewService.fetch(cri);
        //当记录没有时组装数据
        if (ObjectUtil.isEmpty(formSummaryNew)) {
            SqfwShopsBaseInfo info = shopsBaseInfoService.fetch(shopBaseInfoId);
            if (ObjectUtils.isEmpty(info)) {
                throw new ServiceException("场所信息不存在！");
            }
            Sqfw_formSummary_new formSummaryNewBuild = new Sqfw_formSummary_new();
            SafeCheckTaskPdfDTO safeCheckTaskPdfDTO = new SafeCheckTaskPdfDTO();
            safeCheckTaskPdfDTO.setType(info.getType());
            safeCheckTaskPdfDTO.setPlaceType(info.getMainBusinessScope());
            safeCheckTaskPdfDTO.setPlaceName(info.getPlaceName());
            safeCheckTaskPdfDTO.setAddress(info.getAddress());
            safeCheckTaskPdfDTO.setMainBusinessScope(info.getMainBusinessScope());
            safeCheckTaskPdfDTO.setOperatorTelephone(info.getOperatorTelephone());
            safeCheckTaskPdfDTO.setSiteManager(info.getOperator());
            safeCheckTaskPdfDTO.setHiddenDanger(Lists.newArrayList());
            formSummaryNewBuild.setParamData(JSON.toJSONString(safeCheckTaskPdfDTO));
            formSummaryNewBuild.setShopsBaseInfoId(info.getId());
            formSummaryNewBuild.setShopsBaseInfo(info);
            return Result.data(formSummaryNewBuild);
        }
        return Result.data(formSummaryNew);
    }

    @Override
    public Result<?> getReportMaterials(String startTime, String endTime, String serviceType, String shopInfoId, String placeType) {
        if (StringUtils.isBlank(serviceType)) {
            throw new ServiceException("业务类型不能为空！");
        }


        Cnd cnd = Cnd.NEW();
        //SqlExpressionGroup expressionGroup = cnd.where();
        //expressionGroup.and(Sqfw_formSummary_new::getCreateBy, "=", SecurityUtil.getUserId());
        cnd.and("type", "=", serviceType);
        if (StringUtils.isNotBlank(startTime)) {
            cnd.and(Sqfw_formSummary_new::getFillDate, ">", String.format("%s 00:00:00", startTime));
        }
        if (StringUtils.isNotBlank(endTime)) {
            cnd.and(Sqfw_formSummary_new::getFillDate, "<", String.format("%s 23:59:59", endTime));
        }
        if (StringUtils.isNotBlank(placeType)) {
            cnd.and("param_data ->>'placeType'", "in", Arrays.asList(placeType.split(",")));
        }
        Sys_user user = userService.getUserById(SecurityUtil.getUserId());
        //拼接五级 省
        cnd.and(Sqfw_formSummary_new::getProvince, "=", user.getProvince());
        //拼接五级 市
        cnd.and(Sqfw_formSummary_new::getCity, "=", user.getCity());
        //拼接五级 区
        cnd.and(Sqfw_formSummary_new::getDistrict, "=", user.getDistrict());
        //拼接五级 街道
        cnd.and(Sqfw_formSummary_new::getCounty, "=", user.getCounty());
        //拼接五级 社区
        cnd.and(Sqfw_formSummary_new::getCommunity, "=", user.getCommunity());
        if (StringUtils.isNotBlank(shopInfoId)) {
            cnd.and(Sqfw_formSummary_new::getShopsBaseInfoId, "=", shopInfoId);
        }
        log.info("开始查询时间0：" + new Date());
        List<Sqfw_formSummary_new> formSummaryList = sqfwFormsummaryNewService.query(cnd);
        log.info("结束查询时间0：" + new Date());
        List<String> typeList = formSummaryList.stream().map(m -> JSONObject.parseObject(m.getParamData(), SafeCheckTaskPdfDTO.class).getType()).distinct().collect(Collectors.toList());

        //组合pdf跟excel
        List<DownFileTypesResVo> downFileTypesResVoList = Lists.newArrayList();
        int num = 0;
        //如果其他街道要继用在对应街道下加权限
        /** 金阳街道除了基础类还有自己独有的文件 {@link JinYangExcelEnum} */
        Set<String> jinYangCountySet = Sets.newHashSet("金阳街道");
        /** 云潭街道除了基础类还有自己独有的文件 {@link YuHongEnum} */
        Set<String> yunTanCountySet = Sets.newHashSet("云潭街道");
        /** 宾阳除了基础类还有自己独有的文件,观山街道继承宾阳街道部分文件 {@link BinYangFileServiceEnum} */
        Set<String> countySet = Sets.newHashSet("宾阳街道", "观山街道");
        //一下几个文件只有宾阳有，由于观山街道继用了宾阳街道的，因此这几个文件要隔离开
        Set<String> binYangCountySet = Sets.newHashSet("宾阳街道");//宾阳街道除了基础类还有自己独有的文件
        Set<String> fileCode = Sets.newHashSet(BinYangFileServiceEnum.THREE_PDF.getCode(), BinYangFileServiceEnum.THREE_EXCEL.getCode(),
                BinYangFileServiceEnum.FORE_PDF.getCode(), BinYangFileServiceEnum.FORE_EXCEL.getCode());
        //只有世纪城有这个文件
        Set<String> centuryCityCountySet = Sets.newHashSet("世纪城街道");//世纪城街道除了基础类还有自己独有的文件
        /** 学校食堂食品安全专项监督检查表合集 {@link SafetyCheckV2Enums} */
        Set<String> centuryCityFileCode = Sets.newHashSet(String.valueOf(SafetyCheckV2Enums.L.getCode()));
        //已添加过的文件，对应街道不用再添加
        Set<String> addFileCode = Sets.newHashSet();
        //基础excel
        for (CenturyCitySafeServiceEnum item : CenturyCitySafeServiceEnum.values()) {
            if (!addFileCode.contains(item.getCode())) {
                //世纪城的作为基础类，先去对应街道excel找，找不到才使用基础类
                if (jinYangCountySet.contains(user.getCounty())) {
                    JinYangExcelEnum jinYangEnumBySplit = JinYangExcelEnum.getJinYangEnumBySplit(item.getCode());
                    if (ObjectUtils.isNotEmpty(jinYangEnumBySplit)) {
                        buildJinYangFile(downFileTypesResVoList, addFileCode, jinYangEnumBySplit, num++);
                        continue;
                    }
                }
                buildCommonFile(downFileTypesResVoList, addFileCode, item, num++);
            }
        }

        //只有云潭有这个文件
        if (yunTanCountySet.contains(user.getCounty())) {
            // 增加宇虹社区欠薪风险表
            for (YuHongEnum item : YuHongEnum.values()) {
                if (!addFileCode.contains(item.getCode())) {
                    buildYunTanFile(downFileTypesResVoList, addFileCode, item, num++);
                }
            }
            //金阳
        } else if (jinYangCountySet.contains(user.getCounty())) {
            // 增加金阳街道燃气使用统计表
            for (JinYangExcelEnum item : JinYangExcelEnum.values()) {
                if (!addFileCode.contains(item.getCode())) {
                    buildJinYangFile(downFileTypesResVoList, addFileCode, item, num++);
                }
            }
        } else if (countySet.contains(user.getCounty())) {
            //宾阳街道、观山街道
            for (BinYangFileServiceEnum item : BinYangFileServiceEnum.values()) {
                if (!addFileCode.contains(item.getCode())) {
                    //只有宾阳有这个文件
                    if (fileCode.contains(item.getCode()) && !binYangCountySet.contains(user.getCounty())) {
                        continue;
                    }
                    buildBinYangFile(downFileTypesResVoList, addFileCode, item, num++);
                }
            }
        }

        //PDF
        for (SafetyCheckV2Enums item : SafetyCheckV2Enums.values()) {
            if (!addFileCode.contains(String.valueOf(item.getCode()))) {
                //只有世纪城有这个文件
                if (centuryCityFileCode.contains(String.valueOf(item.getCode())) && !centuryCityCountySet.contains(user.getCounty())) {
                    continue;
                }
                buildCommonPdfFile(downFileTypesResVoList, addFileCode, item, num++);
            }
        }
        AtomicInteger count = new AtomicInteger(0);
        int noHaveData = 0;
        //List<String> idList = formSummaryList.stream().map(Sqfw_formSummary_new::getSqfwId).distinct().collect(Collectors.toList());
        log.info("开始检测时间1：" + new Date());
        for (DownFileTypesResVo downFileTypesResVo : downFileTypesResVoList) {
            //filePath此字段作为临时使用存入类型
            if (typeList.contains(downFileTypesResVo.getFilePath())) {
                executorService.execute(() -> {
                    //downFileTypesResVo.setIds(idList);
                    try {
                        isHaveData(downFileTypesResVo, formSummaryList);
                       /* if (downFileTypesResVo.isHiveData()) {
                            //使用 0 是为了兼容在下载时接口需要此参数判断是否有下载的数据
                            downFileTypesResVo.setIds(List.of("0"));
                        }*/
                    } catch (Exception e) {
                        log.error("安全排查检查数据异常：" + e.getMessage());
                    }
                    count.incrementAndGet();
                });
            } else {
                noHaveData++;
            }
        }
        while ((count.get() + noHaveData) < downFileTypesResVoList.size()) {
        }
        log.info("结束检测时间1：" + new Date());

        List<DownFileTypesResVo> dftrList = downFileTypesResVoList.stream().sorted(Comparator.comparing(DownFileTypesResVo::getLocation)).collect(Collectors.toList());
        // 组装返回参数
        Pagination pagination = new Pagination();
        pagination.setList(dftrList);
        pagination.setTotalCount(formSummaryList.size());
        return Result.data(pagination);
    }

    private void buildCommonPdfFile(List<DownFileTypesResVo> downFileTypesResVoList, Set<String> addFileCode, SafetyCheckV2Enums item, int num) {
        DownFileTypesResVo downFileTypesResVo = new DownFileTypesResVo();
        downFileTypesResVo.setFileName(String.format("%s.pdf", item.getMergePdf()));
        downFileTypesResVo.setFileType("pdf");
        downFileTypesResVo.setLabel(item.getLabel());
        downFileTypesResVo.setFileCode(String.valueOf(item.getCode()));
        downFileTypesResVo.setHiveData(false);
        downFileTypesResVo.setIds(Lists.newArrayList());
        downFileTypesResVo.setFilePath(item.getName());
        if (StringUtils.isNotBlank(item.getPreviewImage())) {
            downFileTypesResVo.setPreviewImage(Arrays.asList(item.getPreviewImage().split(",")));
        } else {
            downFileTypesResVo.setPreviewImage(Lists.newArrayList());
        }
        downFileTypesResVo.setLocation(num);
        downFileTypesResVoList.add(downFileTypesResVo);
        addFileCode.add(String.valueOf(item.getCode()));
    }

    private void buildBinYangFile(List<DownFileTypesResVo> downFileTypesResVoList, Set<String> addFileCode, BinYangFileServiceEnum item, int num) {
        String suffix = item.getFilePath().split("\\.")[1];
        String fileType = "docx".equals(suffix) ? "pdf" : suffix;
        DownFileTypesResVo downFileTypesResVo = new DownFileTypesResVo();
        downFileTypesResVo.setFileName(String.format("%s.%s", item.getFileName(), fileType));
        downFileTypesResVo.setFileType("pdf".equals(fileType) ? fileType : "excel");
        downFileTypesResVo.setLabel(item.getLabel());
        downFileTypesResVo.setFileCode(String.valueOf(item.getCode()));
        downFileTypesResVo.setHiveData(false);
        downFileTypesResVo.setIds(Lists.newArrayList());
        downFileTypesResVo.setFilePath(item.getLabel());
        if (StringUtils.isNotBlank(item.getPreviewImage())) {
            downFileTypesResVo.setPreviewImage(Arrays.asList(item.getPreviewImage().split(",")));
        } else {
            downFileTypesResVo.setPreviewImage(Lists.newArrayList());
        }
        downFileTypesResVo.setLocation(num);
        downFileTypesResVoList.add(downFileTypesResVo);
        addFileCode.add(item.getCode());
    }

    private void buildCommonFile(List<DownFileTypesResVo> downFileTypesResVoList, Set<String> addFileCode, CenturyCitySafeServiceEnum item, int num) {
        DownFileTypesResVo downFileTypesResVo = new DownFileTypesResVo();
        downFileTypesResVo.setFileName(String.format("%s.xlsx", item.getFileName()));
        downFileTypesResVo.setFileType("excel");
        downFileTypesResVo.setLabel(item.getLabel());
        downFileTypesResVo.setFileCode(item.getCode());
        downFileTypesResVo.setHiveData(false);
        downFileTypesResVo.setIds(Lists.newArrayList());
        downFileTypesResVo.setFilePath(item.getType());
        if (StringUtils.isNotBlank(item.getPreviewImage())) {
            downFileTypesResVo.setPreviewImage(Arrays.asList(item.getPreviewImage().split(",")));
        } else {
            downFileTypesResVo.setPreviewImage(Lists.newArrayList());
        }
        downFileTypesResVo.setLocation(num);
        downFileTypesResVoList.add(downFileTypesResVo);
        addFileCode.add(item.getCode());
    }

    private void buildYunTanFile(List<DownFileTypesResVo> downFileTypesResVoList, Set<String> addFileCode, YuHongEnum item, int num) {
        String suffix = item.getTemplatePath().split("\\.")[1];
        String fileType = "docx".equals(suffix) ? "pdf" : suffix;
        DownFileTypesResVo downFileTypesResVo = new DownFileTypesResVo();
        downFileTypesResVo.setFileName(String.format("%s.%s", item.getFileName(), suffix));
        downFileTypesResVo.setFileType("pdf".equals(fileType) ? fileType : "excel");
        downFileTypesResVo.setLabel(item.getLabel());
        downFileTypesResVo.setFileCode(String.valueOf(item.getCode()));
        downFileTypesResVo.setHiveData(false);
        downFileTypesResVo.setIds(Lists.newArrayList());
        downFileTypesResVo.setFilePath(item.getType());
        if (StringUtils.isNotBlank(item.getPreviewImage())) {
            downFileTypesResVo.setPreviewImage(Arrays.asList(item.getPreviewImage().split(",")));
        } else {
            downFileTypesResVo.setPreviewImage(Lists.newArrayList());
        }
        downFileTypesResVo.setLocation(num);
        downFileTypesResVoList.add(downFileTypesResVo);
        addFileCode.add(item.getCode());
    }

    private void buildJinYangFile(List<DownFileTypesResVo> downFileTypesResVoList, Set<String> addFileCode, JinYangExcelEnum item, int num) {
        String suffix = item.getTemplatePath().split("\\.")[1];
        String fileType = "docx".equals(suffix) ? "pdf" : suffix;
        DownFileTypesResVo downFileTypesResVo = new DownFileTypesResVo();
        downFileTypesResVo.setFileName(String.format("%s.%s", item.getFileName(), suffix));
        downFileTypesResVo.setFileType("pdf".equals(fileType) ? fileType : "excel");
        downFileTypesResVo.setLabel(item.getLabel());
        downFileTypesResVo.setFileCode(String.valueOf(item.getCode()));
        downFileTypesResVo.setHiveData(false);
        downFileTypesResVo.setIds(Lists.newArrayList());
        downFileTypesResVo.setFilePath(item.getType());
        if (StringUtils.isNotBlank(item.getPreviewImage())) {
            downFileTypesResVo.setPreviewImage(Arrays.asList(item.getPreviewImage().split(",")));
        } else {
            downFileTypesResVo.setPreviewImage(Lists.newArrayList());
        }
        downFileTypesResVo.setLocation(num);
        downFileTypesResVoList.add(downFileTypesResVo);
        addFileCode.add(item.getCode());
    }

    private void isHaveData(DownFileTypesResVo downFileTypesResVo, List<Sqfw_formSummary_new> summaryNewList) {
        String fileCode = downFileTypesResVo.getFileCode();
        if (fileCode.equals(CenturyCitySafeServiceEnum.CENTER_CITY_GAS_SAFE.getCode())) {
            //燃气相关
            List<Sqfw_formSummary_new> sqfwFormSummaryNews = summaryNewList.stream().filter(s -> CenturyCitySafeServiceEnum.CENTER_CITY_GAS_SAFE.getType().equals(JSONObject.parseObject(s.getParamData(), SafeCheckTaskPdfDTO.class).getType())).collect(Collectors.toList());
            for (Sqfw_formSummary_new sqfwItem : sqfwFormSummaryNews) {
                SafeCheckTaskPdfDTO safeCheckTaskPdfDTO = JSONObject.parseObject(sqfwItem.getParamData(), SafeCheckTaskPdfDTO.class);
                SafeCheckGasDTO safeCheckGasDTO = safeCheckTaskPdfDTO.getSafeCheckGasDTO();
                if (ObjectUtils.isEmpty(safeCheckGasDTO)) continue;
                CenturyCitySafeCheckGasUseEnum centuryCitySafeCheckGasUseEnum = CenturyCitySafeCheckGasUseEnum.getEnum(safeCheckGasDTO.getFireAndElectricityUsage());
                if (ObjectUtils.isNotEmpty(centuryCitySafeCheckGasUseEnum)) {
                    downFileTypesResVo.setHiveData(true);
                    break;
                }
            }
        } else if (fileCode.equals(String.valueOf(SafetyCheckV2Enums.G.getCode())) ||
                fileCode.equals(String.valueOf(SafetyCheckV2Enums.K.getCode())) ||
                fileCode.equals(CenturyCitySafeServiceEnum.CENTER_CITY_FOOD_SAFE.getCode())) {
            //食品相关
            List<Sqfw_formSummary_new> sqfwFormSummaryNews = summaryNewList.stream().filter(s -> CenturyCitySafeServiceEnum.CENTER_CITY_FOOD_SAFE.getType().equals(JSONObject.parseObject(s.getParamData(), SafeCheckTaskPdfDTO.class).getType()) &&
                    (ObjectUtils.isEmpty(JSONObject.parseObject(s.getParamData(), SafeCheckTaskPdfDTO.class).getFileOutputType()) ||
                            !JSONObject.parseObject(s.getParamData(), SafeCheckTaskPdfDTO.class).getFileOutputType().contains("-1")) &&
                    ObjectUtils.isNotEmpty(JSONObject.parseObject(s.getParamData(), SafeCheckTaskPdfDTO.class).getTransferToMarketSupervisionAndManagement())).collect(Collectors.toList());
            if (!sqfwFormSummaryNews.isEmpty()) {
                //食品excel
                if (CenturyCitySafeServiceEnum.CENTER_CITY_FOOD_SAFE.getCode().equals(fileCode)) {
                    downFileTypesResVo.setHiveData(true);
                } else {
                    for (Sqfw_formSummary_new sfn : sqfwFormSummaryNews) {
                        SafeCheckTaskPdfDTO safeCheckTaskPdfDTO = JSONObject.parseObject(sfn.getParamData(), SafeCheckTaskPdfDTO.class);
                        //这里为了兼容老数据因此是空的情况下之前的都会生成
                        if (ObjectUtil.isEmpty(safeCheckTaskPdfDTO.getFileOutputType()) || safeCheckTaskPdfDTO.getFileOutputType().isEmpty()
                                || safeCheckTaskPdfDTO.getFileOutputType().contains(fileCode)) {
                            downFileTypesResVo.setHiveData(true);
                            break;
                        }
                    }
                }
            }
        } else if (fileCode.equals(String.valueOf(SafetyCheckV2Enums.L.getCode()))) {
            //人员密集-食堂
            List<Sqfw_formSummary_new> sqfwFormSummaryNews = summaryNewList.stream().filter(s -> CenturyCitySafeServiceEnum.CENTER_CITY_PERSONNEL_DENSITY.getType().equals(JSONObject.parseObject(s.getParamData(), SafeCheckTaskPdfDTO.class).getType()) &&
                    "true".equals(JSONObject.parseObject(s.getParamData(), SafeCheckTaskPdfDTO.class).getWhetherItIsASchool())).collect(Collectors.toList());
            //食堂
            downFileTypesResVo.setHiveData(!sqfwFormSummaryNews.isEmpty());
        } else if (fileCode.equals(BinYangFileServiceEnum.ONE_EXCEL.getCode())
                || fileCode.equals(BinYangFileServiceEnum.ONE_PDF.getCode())) {
            LargeCompanySafeGenerator safeGenerator = new LargeCompanySafeGenerator();
            List<Sqfw_formSummary_new> exportData = safeGenerator.getExportData(summaryNewList);
            downFileTypesResVo.setHiveData(!exportData.isEmpty());
        } else if (fileCode.equals(BinYangFileServiceEnum.TWO_EXCEL.getCode())
                || fileCode.equals(BinYangFileServiceEnum.TWO_PDF.getCode())) {
            EnterpriseSafetyInvestigationExcel safeGenerator = new EnterpriseSafetyInvestigationExcel();
            List<Sqfw_formSummary_new> exportData = safeGenerator.getExportData(summaryNewList);
            downFileTypesResVo.setHiveData(!exportData.isEmpty());
        } else if (fileCode.equals(BinYangFileServiceEnum.THREE_EXCEL.getCode())
                || fileCode.equals(BinYangFileServiceEnum.THREE_PDF.getCode())) {
            CampusTrainingOffExcel safeGenerator = new CampusTrainingOffExcel();
            List<Sqfw_formSummary_new> exportData = safeGenerator.getExportData(summaryNewList);
            downFileTypesResVo.setHiveData(!exportData.isEmpty());
        } else if (fileCode.equals(BinYangFileServiceEnum.FORE_EXCEL.getCode())
                || fileCode.equals(BinYangFileServiceEnum.FORE_PDF.getCode())) {
            logisticsWarehouseExcelGenerator safeGenerator = new logisticsWarehouseExcelGenerator();
            List<Sqfw_formSummary_new> exportData = safeGenerator.getExportData(summaryNewList);
            downFileTypesResVo.setHiveData(!exportData.isEmpty());
        } else {
            downFileTypesResVo.setHiveData(true);
        }
    }

    private void buildAndAddParamData(List<Sqfw_formSummary_new> result, Set<String> ps, List<SqfwShopsBaseInfo> sqfwShopsBaseInfos) {
        //构建商铺数据
        for (SqfwShopsBaseInfo info : sqfwShopsBaseInfos) {
            if (!ps.contains(info.getId())) {
                Sqfw_formSummary_new formSummaryNew = new Sqfw_formSummary_new();
                SafeCheckTaskPdfDTO safeCheckTaskPdfDTO = new SafeCheckTaskPdfDTO();
                safeCheckTaskPdfDTO.setType(info.getType());
                safeCheckTaskPdfDTO.setPlaceType(info.getMainBusinessScope());
                safeCheckTaskPdfDTO.setPlaceName(info.getPlaceName());
                safeCheckTaskPdfDTO.setAddress(info.getAddress());
                safeCheckTaskPdfDTO.setMainBusinessScope(info.getMainBusinessScope());
                safeCheckTaskPdfDTO.setOperatorTelephone(info.getOperatorTelephone());
                safeCheckTaskPdfDTO.setSiteManager(info.getOperator());
                safeCheckTaskPdfDTO.setHiddenDanger(Lists.newArrayList());
                formSummaryNew.setParamData(JSON.toJSONString(safeCheckTaskPdfDTO));
                formSummaryNew.setShopsBaseInfoId(info.getId());
                formSummaryNew.setShopsBaseInfo(info);
                result.add(formSummaryNew);
            }
        }
    }

    private List<Sqfw_formSummary_new> buildParamData(List<SqfwShopsBaseInfo> sqfwShopsBaseInfos) {
        List<Sqfw_formSummary_new> list = Lists.newArrayList();
        //构建商铺数据
        for (SqfwShopsBaseInfo info : sqfwShopsBaseInfos) {
            Sqfw_formSummary_new formSummaryNew = new Sqfw_formSummary_new();
            SafeCheckTaskPdfDTO safeCheckTaskPdfDTO = new SafeCheckTaskPdfDTO();
            safeCheckTaskPdfDTO.setType(info.getType());
            safeCheckTaskPdfDTO.setPlaceType(info.getMainBusinessScope());
            safeCheckTaskPdfDTO.setPlaceName(info.getPlaceName());
            safeCheckTaskPdfDTO.setAddress(info.getAddress());
            safeCheckTaskPdfDTO.setMainBusinessScope(info.getMainBusinessScope());
            safeCheckTaskPdfDTO.setOperatorTelephone(info.getOperatorTelephone());
            safeCheckTaskPdfDTO.setSiteManager(info.getOperator());
            safeCheckTaskPdfDTO.setHiddenDanger(Lists.newArrayList());
            formSummaryNew.setParamData(JSON.toJSONString(safeCheckTaskPdfDTO));
            formSummaryNew.setShopsBaseInfoId(info.getId());
            formSummaryNew.setShopsBaseInfo(info);
            list.add(formSummaryNew);
        }
        return list;
    }
}
